<template>
  <div class="sky-swiper" id="sky-swiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="item in list" :key="item.id">
        <div class="swiper-slide-content">
          <p>{{ item.title }}</p>
          <div
            v-if="item.longPage"
            style="height: 1200px; background-color: orange"
          ></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue'
declare const Swiper: any

const handleSwiper = () => {
  onMounted(() => {
    ;(document.getElementById('sky-swiper') as HTMLElement).style.height =
      document.documentElement.clientHeight + 'px'

    const swiper = new Swiper('#sky-swiper', {
      direction: 'vertical',
    })

    let startScroll = 0
    let touchStart = 0
    let touchCurrent = 0

    swiper.slides.on(
      'touchstart',
      (e: any) => {
        const path = e.path
        const event = path.find((item: any) => {
          return item.className.includes('swiper-slide')
        })
        startScroll = event.scrollTop
        touchStart = e.targetTouches[0].pageY
      },
      true
    )
    //
    swiper.slides.on(
      'touchmove',
      (e: any) => {
        touchCurrent = e.targetTouches[0].pageY
        const touchesDiff = touchCurrent - touchStart

        const path = e.path

        const slide = path.find((item: any) => {
          return item.className.includes('swiper-slide')
        })

        const onlyScrolling =
          slide.scrollHeight > slide.offsetHeight &&
          ((touchesDiff < 0 && startScroll === 0) ||
            (touchesDiff > 0 &&
              startScroll === slide.scrollHeight - slide.offsetHeight) ||
            (startScroll > 0 &&
              startScroll < slide.scrollHeight - slide.offsetHeight))

        if (onlyScrolling) {
          e.stopPropagation()
        }
      },
      true
    )
    //
  })
}

export default defineComponent({
  name: 'Home',
  setup() {
    const list = ref([
      {
        id: 1,
        title: '我是第一页',
        longPage: false,
      },
      {
        id: 2,
        title: '我是第二页',
        longPage: false,
      },
      {
        id: 3,
        title: '我是第三页，是一个长页面，本身要滚动',
        longPage: true,
      },
      {
        id: 4,
        title: '我是第四页',
        longPage: false,
      },
    ])

    handleSwiper()
    return {
      list,
    }
  },
})
</script>

<style lang="less" scoped>
.swiper-slide-content {
  position: relative;
  height: 100%;
  overflow-x: hidden;
  overflow-y: auto;
  box-sizing: border-box;
}
</style>
